<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="my-position">我的当前位置：</div>

    <button onclick="myGetCurrentPosition()">getCurrentPosition 获取位置</button>
    <button onclick="myWatchPosition()">watchPosition 获取位置</button>

    <script>
        var divObj = document.getElementById("my-position");
        function myGetCurrentPosition() {
            if (navigator.geolocation) {
                // getCurrentPosition 
                navigator.geolocation.getCurrentPosition(showPosition, showError);
            }
        }
        function showPosition(position) {
            divObj.innerHTML = "经度=" + position.coords.longitude +
                ",纬度=" + position.coords.latitude;
        }
        // 获取位置失败的处理
        function showError(positionError) {
            switch (positionError.code) {
                case positionError.PERMISSION_DENIED:
                    //  
                    divObj.innerHTML = "权限不足，获取位置失败";
                    break;
                case positionError.POSITION_UNVAILABLE:
                    //
                    divObj.innerHTML = "位置不可用，获取位置失败";
                    break;
                case positionError.TIMEOUT:
                    //
                    divObj.innerHTML = "超时，获取位置失败";
                    break;
                case positionError.UNKNOWN_ERROR:
                    //
                    divObj.innerHTML = "未知错误，获取位置失败";
                    break;
            }
        }
        function myWatchPosition() {
            if (navigator.geolocation) {
                // watchPosition
                navigator.geolocation.watchPosition(showPosition,showError);
            }
        }
    </script>
</body>

</html>